<template>
  <div class="app-container">
    <div class="table-box">
      <!-- 搜索区 开始 -->
      <div class="search-box">
        <el-form ref="listQuery" :model="listQuery" label-width="90px">
          <el-row>
            <el-col :xs="24" :sm="20" :md="20" :lg="20" :xl="20">
              <el-row>
                <!-- 表单元素 开始 -->
                <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                  <el-form-item
                    :label="$t('common.status')"
                    prop="status"
                    class="select-class"
                  >
                    <el-select
                      v-model="listQuery.status"
                      :placeholder="$t('common.pleaseSelect')"
                      clearable
                    >
                      <el-option
                        v-for="item in dictionaryService.getItems('statusVar')"
                        :key="item.id"
                        :label="item.name"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                  <el-form-item
                    :label="$t('common.keywords')"
                    prop="keywords_value"
                  >
                    <el-input
                      v-model="listQuery.keywords_value"
                      :placeholder="
                        $t('common.pleaseEnter') + $t('common.keywords')
                      "
                      class="input-with-select"
                      clearable
                      @keyup.enter.native="handleFilter"
                    >
                      <el-select
                        slot="prepend"
                        v-model="listQuery.keywords_key"
                        :placeholder="$t('common.pleaseSelect')"
                        style="width: 105px"
                      >
                        <el-option
                          v-for="item in keywordKeysOptions"
                          :key="item.id"
                          :label="item.text"
                          :value="item.id"
                        />
                      </el-select>
                    </el-input>
                  </el-form-item>
                </el-col>
                <!-- 表单元素 开始 -->
              </el-row>
            </el-col>
            <el-col :xs="24" :sm="4" :md="4" :lg="4" :xl="4" class="search-btn">
              <el-button v-waves type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('common.search') }}</el-button>
              <el-button icon="el-icon-refresh" @click="handleResetFilter">{{ $t('common.reset') }}</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 搜索区 结束 -->

      <!-- 按钮功能区 开始 -->
      <el-row :gutter="10" class="btn-box">
        <el-col
          :xs="24"
          :sm="24"
          :md="24"
          :lg="24"
          :xl="24"
          class="btnfunction-section-col"
        >
          <el-button type="primary" icon="el-icon-plus" :disabled="!checkPermission(['admin.role.store'])" @click="handleCreate()">{{
            $t('common.create')
          }}</el-button>
          <el-button plain type="danger" icon="el-icon-delete" :disabled="!checkPermission(['admin.role.destroy'])" @click="handleAllDelete()">{{ $t('common.delete') }}</el-button>
          <el-button type="primary" icon="awesome-icon fas fa-sort" :disabled="!checkPermission(['admin.role.updateSort'])" @click="handleUpdateSort()">
            {{ $t('common.updateSort') }}
          </el-button>
        </el-col>
      </el-row>
      <!-- 按钮功能区 结束 -->
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%"
        max-height="540"
        @sort-change="sortChange"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center" fixed="left" />
        <el-table-column
          :label="$t('common.id')"
          prop="id"
          sortable="custom"
          align="center"
          width="80"
          :class-name="getSortClass('id')"
        >
          <template slot-scope="{ row }">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('role.name')"
          min-width="100"
          align="center"
        >
          <template slot-scope="{ row }"> {{ row.name }} </template>
        </el-table-column>
        <el-table-column
          :label="$t('role.description')"
          min-width="100"
          align="center"
        >
          <template slot-scope="{ row }">
            {{ row.description }}
          </template>
        </el-table-column>
        <el-table-column width="180" :label="$t('common.sort')" align="center">
          <template slot-scope="{ row }">
            <el-input-number v-model="row.sort" controls-position="right" :min="1" />
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('common.status')"
          class-name="status-col"
          width="100"
        >
          <template slot-scope="{ row }">

            <el-switch
              v-model.number="row.status"
              :active-value="1"
              :inactive-value="0"
              :disabled="!checkPermission(['admin.role.updateStatus'])"
              @change="handleModifyStatus($event,row)"
            />

          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.created_at')"
          width="200px"
          align="center"
        >
          <template slot-scope="{ row }">
            <span>{{ row.created_at }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.operation')"
          align="center"
          width="200"
          class-name="small-padding fixed-width"
          fixed="right"
        >
          <template slot-scope="{ row, $index }">
            <el-link
              type="primary"
              :underline="false"
              :disabled="!checkPermission(['admin.user.roleUserList'])"
              icon="awesome-icon fas fa-users"
              :title="$t('role.users')"
              @click="handleShowUsers(row)"
            >{{ $t('role.users') }}
            </el-link>&nbsp;
            <el-link
              type="primary"
              :underline="false"
              :disabled="!checkPermission(['admin.role.update'])&&!checkPermission(['admin.role.show'])"
              icon="el-icon-edit"
              :title="$t('common.edit')"
              @click="handleEdit(row)"
            >{{ $t('common.edit') }}
            </el-link>&nbsp;
            <el-link
              type="primary"
              :underline="false"
              :disabled="!checkPermission(['admin.role.destroy'])"
              icon="el-icon-delete"
              :title="$t('common.delete')"
              @click="handleDelete(row, $index)"
            >{{ $t('common.delete') }}
            </el-link>&nbsp;
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页功能 开始 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
      <!-- 分页功能 结束 -->
    </div>

    <!--管理员列表开始-->
    <el-dialog :title="dialog_role.name+'-'+$t('role.users')" :visible.sync="dialogUsersTableVisible" destroy-on-close custom-class="jsp-dialog-modal-box userListDialog" @click="handleUsersDialogClose">

      <div class="search-box">
        <el-form ref="usersListQuery" :model="usersListQuery" label-width="90px">
          <el-row>
            <el-col :xs="24" :sm="18" :md="18" :lg="18" :xl="18">
              <el-row>
                <el-col :xs="24" :sm="17" :md="17" :lg="17" :xl="17">
                  <el-form-item
                    :label="$t('common.keywords')"
                    prop="keywords_value"
                  >
                    <el-input
                      v-model="usersListQuery.keywords_value"
                      :placeholder="
                        $t('role.users_keywords_tips')
                      "
                      class="input-with-select"
                      clearable
                      @keyup.enter.native="handleUsersFilter"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
            <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6" class="search-btn">
              <el-button v-waves type="primary" icon="el-icon-search" @click="handleUsersFilter">{{ $t('common.search') }}</el-button>
              <el-button @click="handleUsersResetFilter">{{ $t('common.reset') }}</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <el-table
        :key="usersTableKey"
        v-loading="usersListLoading"
        :data="usersList"
        border
        fit
        highlight-current-row
        style="width: 100%"
        max-height="540"
        @sort-change="usersSortChange"
      >
        <el-table-column
          :label="$t('common.id')"
          prop="id"
          sortable="custom"
          align="center"
          width="80"
          :class-name="getUsersSortClass('id')"
          fixed="left"
        >
          <template slot-scope="{ row }">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.username')"
          min-width="150"
          align="center"
          fixed="left"
        >
          <template slot-scope="{ row }">
            {{ row.username }}
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('common.name_ext')"
          min-width="150"
          align="center"
        >
          <template slot-scope="{ row }"> {{ row.name }} </template>
        </el-table-column>

        <el-table-column
          :label="$t('common.phone_number')"
          align="center"
          min-width="150"
        >
          <template slot-scope="{ row }">
            {{ row.phone_number }}
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('common.email')"
          align="center"
          min-width="150"
        >
          <template slot-scope="{ row }">
            {{ row.email }}
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('user.login_fail_times')"
          class-name="status-col"
          width="200"
        >
          <template slot-scope="{ row }">
            <span>
              {{ row.login_fail_times }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('user.last_login_time')"
          width="200px"
          align="center"
        >
          <template slot-scope="{ row }">
            <span>{{ row.last_login_time }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.status')"
          class-name="status-col"
          width="100"
        >
          <template slot-scope="{ row }">
            <span>{{ row.status | paraseDictionaryItemName('statusVar') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.created_at')"
          width="200px"
          align="center"
        >
          <template slot-scope="{ row }">
            <span>{{ row.created_at }}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="usersTotal > 0"
        :total="usersTotal"
        :page.sync="usersListQuery.page"
        :limit.sync="usersListQuery.limit"
        @pagination="getRoleUsersList"
      />

      <div class="clearUserlistFloat">&nbsp;</div>

    </el-dialog>

  <!--管理员列表结束-->

  </div>
</template>

<script>
import { index, updateStatus, destory, updateSort } from '@/api/role'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getRoleUserList } from '@/api/user'
import checkPermission from '@/utils/permission'

export default {
  name: 'RoleIndex',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        sort: '+sort',
        status: '',
        keywords_key: 'name',
        keywords_value: ''
      },
      keywordKeysOptions: [{ id: 'name', text: this.$t('role.name') }],
      multipleSelection: [],
      // 管理员列表配置
      dialogUsersTableVisible: false,
      usersTableKey: 1,
      usersList: [],
      usersTotal: 0,
      usersListLoading: true,
      usersListQuery: {
        page: 1,
        limit: 20,
        sort: '-id',
        status: '',
        keywords_value: ''
      },
      usersKeywordKeysOptions: [{ id: 'name', text: this.$t('role.name') }],
      //
      dialog_role: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    checkPermission,
    async getList() {
      this.listLoading = true
      await index(this.listQuery).then((response) => {
        this.list = response.data.items
        this.total = response.data.meta.total
        this.listLoading = false
      }).catch(() => {
        this.closeBack()
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleResetFilter() {
      this.listQuery.page = 1
      this.$refs['listQuery'].resetFields()
      this.getList()
    },
    handleModifyStatus($event, row) {
      updateStatus(row.id, { status: $event }).then((response) => {
        this.$message.success(response.message)
        row.status = $event
      }).catch(() => {
      })
    },
    sortChange(data) {
      const { prop, order } = data
      if (order === 'ascending') {
        this.listQuery.sort = '+' + prop
      } else if (order === 'descending') {
        this.listQuery.sort = '-' + prop
      } else {
        this.listQuery.sort = ''
      }
      this.listQuery.sort && this.handleFilter()
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      if (sort === `+${key}`) {
        return 'ascending'
      } else if (sort === `-${key}`) {
        return 'descending'
      } else {
        return ''
      }
    },
    handleDelete(row, index) {
      this.$confirm(this.$t('common.delete_confirm_tips'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      })
        .then(() => {
          destory(row.id).then((response) => {
            this.$message.success(response.message)
            this.list.splice(index, 1)
          }).catch(() => {
          })
        })
        .catch(() => {
          this.$message.info(this.$t('common.canceled'))
        })
    },
    handleCreate() {
      this.$router.push({ name: 'RoleCreate' })
    },
    handleEdit(row) {
      this.$router.push({ name: 'RoleEdit', params: { id: row.id }})
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleAllDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning(this.$t('common.delete_items_tips'))
        return
      }
      this.$confirm(
        this.$t('common.delete_confirm_tips'),
        this.$t('common.warm_tips'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }
      )
        .then(() => {
          const ids = this.multipleSelection.map(function(e) {
            return e.id
          })
          destory(ids).then((response) => {
            this.$message.success(response.message)
            this.getList()
          }).catch(() => {
          })
        })
        .catch(() => {
          this.$message.info(this.$t('common.canceled'))
        })
    },
    handleShowUsers(row) {
      this.dialogUsersTableVisible = true
      this.dialog_role = row
      this.getRoleUsersList()
    },
    async getRoleUsersList() {
      this.usersListLoading = true
      await getRoleUserList(this.dialog_role.id, this.usersListQuery).then((response) => {
        this.usersList = response.data.items
        this.usersTotal = response.data.meta.total
        this.usersListLoading = false
      }).catch(() => {
      })
    },
    usersSortChange(data) {
      const { prop, order } = data
      if (order === 'ascending') {
        this.usersListQuery.sort = '+' + prop
      } else if (order === 'descending') {
        this.usersListQuery.sort = '-' + prop
      } else {
        this.usersListQuery.sort = ''
      }
      this.usersListQuery.sort && this.handleUsersFilter()
    },
    getUsersSortClass: function(key) {
      const sort = this.usersListQuery.sort
      if (sort === `+${key}`) {
        return 'ascending'
      } else if (sort === `-${key}`) {
        return 'descending'
      } else {
        return ''
      }
    },
    handleUsersFilter() {
      this.usersListQuery.page = 1
      this.getRoleUsersList()
    },
    handleUsersResetFilter() {
      this.usersListQuery.page = 1
      this.$refs['usersListQuery'].resetFields()
      this.getRoleUsersList()
    },
    handleUsersDialogClose() {
      this.usersListLoading = false
      this.dialog_role = {}
    },
    handleUpdateSort() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning(this.$t('common.please_choose_sort_tips'))
        return
      }
      const params = this.multipleSelection.map((row, index) => {
        return { id: row.id, sort: row.sort }
      })
      updateSort({ sort: params }).then((response) => {
        this.$message.success(response.message)
        this.getList()
      }).catch(() => {
      })
    }
  }
}
</script>
<style scoped  lang="scss" >
.userListDialog {
  .search-btn {
    text-align: right;
  }
  .clearUserlistFloat {
    clear:both
  }
}

</style>
